package com.comm.db;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

import com.alibaba.common.lang.StringUtil;
import com.comm.db.pojo.RResumebasictable;

/**
 * Configures and provides access to Hibernate sessions, tied to the current
 * thread of execution. Follows the Thread Local Session pattern, see
 * {@link http://hibernate.org/42.html }.
 */
public class SessionFactory {

	/**
	 * Location of hibernate.cfg.xml file. Location should be on the classpath
	 * as Hibernate uses #resourceAsStream style lookup for its configuration
	 * file. The default classpath location of the hibernate config file is in
	 * the default package. Use #setConfigFile() to update the location of the
	 * configuration file for the current session.
	 */
	private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static Configuration configuration = new Configuration();
	private static org.hibernate.SessionFactory sessionFactory;
	private static String configFile = CONFIG_FILE_LOCATION;

	static {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	private SessionFactory() {
	}

	/**
	 * Returns the ThreadLocal Session instance. Lazy initialize the
	 * <code>SessionFactory</code> if needed.
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			System.out.println(session);
	 
			threadLocal.set(session);
		}

		return session;
	}

	/**
	 * Rebuild hibernate session factory
	 * 
	 */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
	 * Close the single hibernate session instance.
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);

		if (session != null) {
			session.close();
		}
	}

	/**
	 * return session factory
	 * 
	 */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * return session factory
	 * 
	 * session factory will be rebuilded in the next call
	 */
	public static void setConfigFile(String configFile) {
		SessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
	 * return hibernate configuration
	 * 
	 */
	public static Configuration getConfiguration() {
		return configuration;
	}

	public static void saveOrUpdate(Object obj) {
		try {
			Session session = SessionFactory.getSession();

			session.beginTransaction().begin();
			session.saveOrUpdate(obj);
			session.beginTransaction().commit();
		} catch (Exception e) {

		} finally {
			closeSession();
		}

	}

	static int count = 0;
	static boolean isCommit = false;

	public static void save(Object obj) throws Exception {
		try {
			Session session = SessionFactory.getSession();
			session.beginTransaction();
			session.save(obj);
			session.beginTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeSession();
		}
	}

	public static void main(String[] args) throws IOException {

		String encoding = "Unicode";
		String filePath = "E:\\HRSystem\\test.txt";
		File file = new File(filePath);
		// FileUtils.readLines(file, encoding);
		List<String> readLinesString = FileUtils.readLines(file, encoding);

		int test = 1;
		for (String line : readLinesString) {
			/*
			 * if (test >13) break;
			 */
			test++;
			String[] s = line.split("}");
			int count = 0;
			System.out.println(test + "---" + line);
			// 转空为0
			for (int i = 0; i < s.length; i++) {
				System.out.println(count++ + ":" + s[i]);
				if (StringUtil.isBlank(s[i]) || StringUtil.equals(s[i], "NULL")) {
					s[i] = "";
				}
			}

			try {
				RResumebasictable resumebasictable = new RResumebasictable();
				resumebasictable.setFromId(s[0]);
				resumebasictable.setUserName(s[1]);
				resumebasictable.setBirthDay(s[2]);
				resumebasictable.setAge(StringUtil.isBlank(s[3]) ? null
						: Integer.valueOf(s[3]));
				resumebasictable.setMarried(StringUtil.isBlank(s[4]) ? null
						: Integer.valueOf(s[4]));
				String ExperienceTimeVal=s[5];
				if (ExperienceTimeVal.length() > 160)
					ExperienceTimeVal = StringUtil.substring(ExperienceTimeVal, 0, 150);
				resumebasictable.setExperienceTimeVal(ExperienceTimeVal);
				
				
			 
				
				resumebasictable.setHighestDegree(s[7]);
				resumebasictable.setCurrentSalary(s[8]);
				resumebasictable.setCountry(s[11]);
				resumebasictable.setNationality(s[12]);
				resumebasictable.setCompanyPhone(s[14]);
				resumebasictable.setMobile(s[15]);
				if (s.length >= 17)
					resumebasictable.setHomePhone(s[16]);
				if (s.length >= 21)
					resumebasictable.setEmail(s[20]);
				if (s.length >= 23)
					resumebasictable.setHobbies(s[22]);
				if (s.length >= 24)
					resumebasictable.setPrize(s[23]);
				if (s.length >= 25)
					resumebasictable.setJobInterest(s[24]);
				if (s.length >= 26)
					resumebasictable.setCertificateName(s[25]);
				if (s.length >= 27)
					resumebasictable.setIndustryName(s[26]);
				if (s.length >= 28)
					resumebasictable.setLanguageName(s[27]);
				if (s.length >= 29)
					resumebasictable.setMajorName(s[28]);
				if (s.length >= 30)
					resumebasictable.setPositionName(s[29]);
				if (s.length >= 32) {
					try {
						resumebasictable
								.setDelTag(StringUtil.isBlank(s[31]) ? null
										: Integer.valueOf(s[31]));
					} catch (Exception e) {

					}
				}
				if (s.length >= 33) {
					String companyName = s[32];				 
					if (companyName.length() > 160)
						companyName = StringUtil.substring(companyName, 0, 250);
					resumebasictable.setCompanyName(companyName);
				}

				if (s.length >= 34)
					resumebasictable.setCurrentCompanyinfo(s[33]);
				if (s.length >= 35){
					String WorkExperience=s[34];
					if (WorkExperience.length() > 330)
						WorkExperience = StringUtil.substring(WorkExperience, 0, 330);				 
					resumebasictable.setWorkExperience(WorkExperience);
				}
					
				if (s.length >= 36)
					resumebasictable.setEdu(s[35]);
				if (s.length >= 37)
					resumebasictable.setLanguageSkill(s[36]);
				if (s.length >= 38)
					resumebasictable.setItSkill(s[37]);
				if (s.length >= 39)
					resumebasictable.setProjectExperience(s[38]);
				if (s.length >= 40)
					resumebasictable.setSelfAssessment(s[39]);
				if (s.length >= 41)
					resumebasictable.setTrainer(s[40]);
				if (s.length >= 42)
					resumebasictable.setOthers(s[41]);
				// insert into db
				if (resumebasictable != null){
					 
					save(resumebasictable);
				}
					
			} catch (Exception e) {
				exception(e, line);
			}

			System.out.println("----------------------" + test);
		}
		isCommit = true;

	}

	 

	static void testsave(RResumebasictable resumebasictable) {
		// save(resumebasictable);
		// saveOrUpdate(resumebasictable);

	}

	static void exception(Exception e, String line) {
		try {
			// 错误写入 文件
			File saveFile = new File("d://error.txt");
			String oldString = FileUtils.readFileToString(saveFile, "utf-8");
			String newLine = "\n";
			line = e.getCause() + line;
			FileUtils.write(saveFile, oldString + newLine + line);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("error line :" + line + "----------");
		e.printStackTrace();

	}

}